import dayjs from 'dayjs';

export const transformDate: (value: string | number) => Date = (value) => {
  if (!value) return;
  let newValue;
  if (typeof value === 'number') {
    newValue = new Date(value);
  }
  // 时间戳
  else if (typeof value === 'string' && value.length === 13) {
    newValue = new Date(dayjs(parseInt(value, 10)).valueOf());
  }
  // 日期 '20120101'
  else {
    newValue = (value as string).replace(
      /(\d{4})[-/]?(\d{2})[-/]?(\d{2})\s?(\d{2})?\s?(\d{2})?/,
      ($0, $1, $2, $3, $4, $5, $6) => {
        const year = $1;
        const month = $2 ? `/${$2}` : '';
        const date = $3 ? `/${$3}` : '';
        const time = $4 ? ` ${$4}` : '';
        const seconds = $5 ? `:${$5}` : '';
        const minutes = $6 ? `:${$6}` : '';
        return `${year}${month}${date}${time}${seconds}${minutes}`;
      },
    );
    newValue = new Date(newValue);
  }
  return newValue;
};
